<template>
  <div style="height: 10vh; background-color: #fff; padding: 10px 20px;">
    <el-card style="height: 100%;">
      <el-form :inline="true" :model="searchForm" @submit.prevent="fetchLogs">
        <el-form-item label="操作人员账号" prop="operatorAccount">
          <el-select v-model="searchForm.operatorAccount" placeholder="请选择操作员账号" style="width: 15vh;" filterable clearable>
            <el-option v-for="admin in adminAccountOptions" :key="admin.value" :label="admin.label" :value="admin.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作人员名称" prop="operatorName">
          <el-select v-model="searchForm.operatorName" placeholder="请选择操作员名称" style="width: 15vh;" filterable clearable>
            <el-option v-for="admin in adminNameOptions" :key="admin.value" :label="admin.label" :value="admin.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="操作类别" prop="operationClass">
          <el-select v-model="searchForm.operationClass" placeholder="请选择操作类别" style="width: 15vh;" filterable clearable>
            <el-option v-for="way in operations" :key="way.value" :label="way.label" :value="way.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form :inline="true">
        <el-form-item>
          <el-button @click="resetQuery">重置</el-button>
          <el-button type="primary" :loading="loading" @click="fetchLogs">查询</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

  <!-- 列表 -->
  <el-card style="margin: 20px;height: 70vh">
    <el-table :data="showList" border v-loading="loading">
      <el-table-column prop="operatorAccount" label="操作人员账号" align="center" width="150" />
      <el-table-column prop="operatorName" label="操作人员名称" align="center" width="150" />
      <el-table-column prop="operationClass" label="操作类别" align="center" width="150" />
      <el-table-column prop="operationContent" label="操作内容" align="center" min-width="300" />
      <el-table-column prop="operationTime" label="操作时间" align="center" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.operationTime) }}
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        layout="total, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
        style="margin-top: 20px;"
    />
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

// 定义后端API接口路径
const API_URL = import.meta.env.VITE_API_BASE_URL

// 静态操作类别选项
const operations = ref([
  { label: '停车场管理', value: '停车场管理' },
  { label: '黑名单管理', value: '黑名单管理' },
  { label: '临停规则', value: '临停规则' },
  { label: '长租规则', value: '长租规则' },
  { label: '月租管理', value: '月租管理' },
  { label: '停车记录', value: '停车记录' },
  { label: '缴费管理', value: '缴费管理' },
  { label: '管理员', value: '管理员' },
  { label: '操作日志', value: '操作日志' },
  { label: '用户登录', value: '用户登录' },
  { label: '用户退出', value: '用户退出' }
])

// 操作人员选项（从 admin 表获取）
const adminAccountOptions = ref([])
const adminNameOptions = ref([])

// 搜索表单
const searchForm = ref({
  operatorAccount: '',
  operatorName: '',
  operationClass: ''
})

// 表格数据和分页相关
const showList = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)


// 获取操作人员选项
const fetchAdminOptions = async () => {
  try {
    const { data } = await axios.get(`${API_URL}/v1/admin/select`)
    if (data.code === 2000) {
      adminAccountOptions.value = data.response.map(admin => ({
        value: admin.account,
        label: admin.account
      }))
      adminNameOptions.value = data.response
          .filter(admin => admin.name)
          .map(admin => ({
            value: admin.name,
            label: admin.name
          }))
    } else {
      ElMessage.error('获取操作人员列表失败')
    }
  } catch (error) {
    ElMessage.error('获取操作人员列表失败')
    console.error('获取操作人员列表失败:', error)
  }
}

// 查询操作日志
const fetchLogs = async () => {
  loading.value = true
  try {
    const params = {
      operatorAccount: searchForm.value.operatorAccount || null,
      operatorName: searchForm.value.operatorName || null,
      operationClass: searchForm.value.operationClass || null,
      page: currentPage.value,
      size: pageSize.value
    }
    console.log('查询参数:', params) // 添加调试日志
    const { data } = await axios.get(`${API_URL}/v1/operationLog/select`, { params })
    if (data.code === 2000) {
      showList.value = data.response || []
      total.value = data.total || showList.value.length
    } else {
      ElMessage.error(`查询失败: ${data.response || '未知错误'}`)
    }
  } catch (error) {
    ElMessage.error('获取操作日志失败')
    console.error('获取操作日志失败:', error.response || error)
  } finally {
    loading.value = false
  }
}

// 重置搜索表单
const resetQuery = () => {
  searchForm.value = {
    operatorAccount: '',
    operatorName: '',
    operationClass: ''
  }
  currentPage.value = 1 // 重置到第一页
  fetchLogs()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchLogs()
}

// 初始化加载
onMounted(async () => {
  await fetchAdminOptions()
  await fetchLogs()
})
</script>